using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ColorDither : MonoBehaviour
{
    public Texture src;
    public Material mat;
    public Texture blueNoiseTex;
    public int iterate = 1;


    [ContextMenu("Exec")]
    private void Exec()
    {
        RenderTexture rt = new RenderTexture(src.width, src.height, 0);
        rt.Create();
        mat.SetInt("_Iterate", iterate);
        mat.SetTexture("_BlueNoiseTex", blueNoiseTex);
        Graphics.Blit(src, rt, mat);

        RenderTexture.active = rt;
        Rect rect = new Rect(0f, 0f, rt.width, rt.height);
        Texture2D tex2D = new Texture2D(rt.width, rt.height, TextureFormat.RGB24, false);
        tex2D.ReadPixels(rect, 0, 0);
        tex2D.Apply();
        
        RenderTexture.active = null;
		rt.Release();
		
        if (File.Exists("Assets/output.jpg"))
            File.Delete("Assets/output.jpg");

        File.WriteAllBytes("Assets/output.jpg", tex2D.EncodeToJPG());
#if UNITY_EDITOR
        UnityEditor.AssetDatabase.Refresh();
#endif
    }
}
